package com.ruben.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.imagepreview.R;
import com.ruben.activity.common.PicturePreviewActivity;
import com.ruben.pojo.ImagePreview;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: MainImageListAdapter
 * @Description: 我还没有写描述
 * @Date: 2020/10/17 0017 0:55
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class MainImageListAdapter extends RecyclerView.Adapter<MainImageListAdapter.ViewHolder> {

    private Context context;
    private List<ImagePreview> listData;

    public MainImageListAdapter(Context context, List<ImagePreview> listData) {
        this.context = context;
        this.listData = listData;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main_image, parent, false));
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Glide.with(context)
                .load(listData.get(position).getUrl())
                .error(R.mipmap.error)
                .placeholder(R.mipmap.loading)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(holder.mainImage);
        holder.mainImage.setOnClickListener(v -> {
            List<String> photoUrls = listData.stream().map(ImagePreview::getUrl).collect(Collectors.toList());
            Intent intent = new Intent(context, PicturePreviewActivity.class);
            // 传入默认打开的图片位置
            intent.putExtra(PicturePreviewActivity.IMAGE_NUM, position);
            // 传入图片路径
            intent.putExtra(PicturePreviewActivity.IMAGES_DATA_LIST, (Serializable) photoUrls);
            // 开始活动，如果已存在于一个为它运行的任务中，就把它移到最前
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return listData == null ? 0 : listData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView mainImage;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mainImage = itemView.findViewById(R.id.item_main_image_image_view_main_image);
        }
    }
}
